<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HookFixChat仅供参考  --管理员界面</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
</head>
<body>
    <div class="container">
        <div class="chat-box">
            <div class="messages" id="messages"></div>
            <div class="input-area">
                <input type="text" id="input" placeholder="输入回复..." autocomplete="off">
                <button id="sendBtn">
                    <span>发送</span>
                    <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                        <path d="M22 2L11 13M22 2l-7 20-4-9-9-4 20-7z"/>
                    </svg>
                </button>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <script>
        const API_BASE = 'http://localhost:3000/api';
        const messagesEl = document.getElementById('messages');
        const inputEl = document.getElementById('input');
        const sendBtn = document.getElementById('sendBtn');

        // Markdown配置
        marked.setOptions({
            highlight: (code, lang) => hljs.highlightAuto(code).value,
            breaks: true
        });

        // 添加消息
        function addMessage(content, isUser) {
            const message = document.createElement('div');
            message.className = `message ${isUser ? 'user' : 'bot'}`;
            
            message.innerHTML = `
                <div class="avatar">${isUser ? '😎' : '🤠'}</div>
                <div class="content">${marked.parse(content)}</div>
            `;

            messagesEl.appendChild(message);
            messagesEl.scrollTop = messagesEl.scrollHeight;
            hljs.highlightAll();
        }

        // WebSocket 连接
        const ws = new WebSocket('ws://localhost:3001');
        let lastMessageId = null; // 用于记录最后一条消息的 ID，避免重复显示

        ws.onmessage = (event) => {
            const message = JSON.parse(event.data);
            if (message.id !== lastMessageId) { // 检查是否是重复消息
                addMessage(message.content, message.role === 'user');
                lastMessageId = message.id; // 更新最后一条消息的 ID
            }
        };

        // 发送回复
        async function sendReply() {
            const reply = inputEl.value.trim();
            if (!reply || sendBtn.disabled) return;

            sendBtn.disabled = true;
            inputEl.value = '';
            addMessage(reply, false);

            try {
                const response = await fetch(`${API_BASE}/admin/reply`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ content: reply })
                });

                const data = await response.json();
                if (!data.success) {
                    addMessage(`**发送失败**: ${data.error}`, false);
                }
            } catch (error) {
                addMessage(`**请求失败**: ${error.message}`, false);
            } finally {
                sendBtn.disabled = false;
                inputEl.focus();
            }
        }

        // 初始化
        sendBtn.addEventListener('click', sendReply);
        inputEl.addEventListener('keypress', e => e.key === 'Enter' && sendReply());

        // 加载所有消息
        fetch(`${API_BASE}/messages`)
            .then(res => res.json())
            .then(messages => {
                messages.forEach(msg => {
                    addMessage(msg.content, msg.role === 'user');
                    lastMessageId = msg.id; // 更新最后一条消息的 ID
                });
            });
    </script>
</body>
</html>